package main

import (
	"bytes"
	"context"
	"log"
	"strings"
	"syscall"

	"github.com/hanwen/go-fuse/v2/fs"
	"github.com/hanwen/go-fuse/v2/fuse"
	"k8s.io/client-go/tools/remotecommand"
)

type Dir struct {
	fs     *KubernetesFS
	parent *Dir
	path   string
	fs.Inode
}

func (d *Dir) Readdir(ctx context.Context) (fs.DirStream, syscall.Errno) {
	// 执行 ls 命令以获取目录内容
	log.Printf("Executing ls command in container %s at path %s", d.fs.container, d.path)
	execRequest := d.fs.clientset.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(d.fs.podName).
		Namespace(d.fs.namespace).
		SubResource("exec").
		Param("container", d.fs.container).
		Param("command", "ls").
		Param("command", d.path).
		Param("stdin", "false").
		Param("stdout", "true").
		Param("stderr", "true").
		Param("tty", "false")

	exec, err := remotecommand.NewSPDYExecutor(d.fs.config, "POST", execRequest.URL())
	if err != nil {
		log.Printf("Failed to create executor: %v", err)
		return nil, syscall.EIO
	}

	var stdout, stderr bytes.Buffer
	err = exec.Stream(remotecommand.StreamOptions{
		Stdout: &stdout,
		Stderr: &stderr,
		Tty:    false,
	})
	if err != nil {
		log.Printf("Error executing command: %v, stderr: %s", err, stderr.String())
		return nil, syscall.EIO
	}

	// 解析输出
	files := strings.Split(strings.TrimSpace(stdout.String()), "\n")
	log.Printf("Files found: %v", files)
	entries := make([]fuse.DirEntry, 0, len(files))
	for _, file := range files {
		if file != "" {
			entries = append(entries, fuse.DirEntry{
				Name: file,
				Mode: 0o755,
			})
		}
	}

	return fs.NewListDirStream(entries), 0
}

// 实现 Lookup 方法
func (d *Dir) Lookup(name string, ctx context.Context) (fs.InodeEmbedder, syscall.Errno) {
	// 执行 ls 命令以查找特定文件
	execRequest := d.fs.clientset.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(d.fs.podName).
		Namespace(d.fs.namespace).
		SubResource("exec").
		Param("container", d.fs.container).
		Param("command", "ls").
		Param("command", d.path+"/"+name).
		Param("stdin", "false").
		Param("stdout", "true").
		Param("stderr", "true").
		Param("tty", "false")

	exec, err := remotecommand.NewSPDYExecutor(d.fs.config, "POST", execRequest.URL())
	if err != nil {
		return nil, syscall.EIO
	}

	var stdout bytes.Buffer
	err = exec.Stream(remotecommand.StreamOptions{
		Stdout: &stdout,
		Tty:    false,
	})
	if err != nil {
		return nil, syscall.EIO
	}

	if strings.TrimSpace(stdout.String()) == "" {
		return nil, syscall.ENOENT // 文件未找到
	}

	// 返回文件的新 Inode
	return &File{
		fs:   d.fs,
		name: name,
	}, 0
}
